package client.handle;

import factory.ProxyFactory;
import factory.RpcClientFactory;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import support.RpcInfo;

import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

//点对点调用使用这个
public class ClienInboundHandle extends SimpleChannelInboundHandler<RpcInfo> {
    static Logger logger = LoggerFactory.getLogger(ClienInboundHandle.class);

    CompletableFuture<RpcInfo> future = null;

    public CompletableFuture<RpcInfo> getFuture() {
        return future;
    }

    public void setFuture(CompletableFuture<RpcInfo> future) {
        this.future = future;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, RpcInfo msg) throws Exception {
        NioSocketChannel channel = (NioSocketChannel) ctx.channel();
        logger.info("读取到服务端返回结果:{}",msg);
        future.complete(msg);
    }

    @Override
    public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
        super.channelUnregistered(ctx);
        NioSocketChannel channel = (NioSocketChannel) ctx.channel();
        InetSocketAddress inetSocketAddress = channel.remoteAddress();

        logger.info("服务端下线通知...准备删除客户端本地缓存...");
        RpcClientFactory.removeCacheCLient(inetSocketAddress);
    }
}
